package com.frame.filters;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

public class SetEncodingFilter implements Filter {

  /**
   * 编码格式
   */
  protected String encoding = null;

  /**
   * filter配置信息
   */
  protected FilterConfig filterConfig = null;

  protected boolean ignore = true;

  public void destroy() {
    this.encoding = null;
    this.filterConfig = null;
  }

  public void doFilter(ServletRequest request, ServletResponse response,
                       FilterChain chain) throws IOException, ServletException {
    if (ignore || (request.getCharacterEncoding() == null)) {
      request.setCharacterEncoding(selectEncoding());
    }
    chain.doFilter(request, response);
  }

  /**
   * filter初始化
   */
  public void init(FilterConfig filterConfig) throws ServletException {

    this.filterConfig = filterConfig;
    this.encoding = filterConfig.getInitParameter("encoding");
    String value = filterConfig.getInitParameter("ignore");
    if (value == null)
      this.ignore = true;
    else if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes"))
      this.ignore = true;
    else
      this.ignore = false;
  }

  protected String selectEncoding() {
    return (this.encoding);
  }

  public FilterConfig getFilterConfig() {
    return filterConfig;
  }

  public void setFilterConfig(FilterConfig filterConfig) {
    this.filterConfig = filterConfig;
  }
}
